package com.uniledger.exchange.home.scheme;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.zxing.util.CodeUtils;
import com.uniledger.commonlib.easymoney.EasyMoneyEditText;
import com.uniledger.commonlib.easymoney.EasyMoneyTextView;
import com.uniledger.commonlib.numberkeyboard.KeyboardUtil;
import com.uniledger.commonlib.util.DisplayUtil;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.glide.GlideApp;
import com.uniledger.exchange.home.ImgUtils;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarAsset;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.wallet.WalletKey;

import org.reactivestreams.Subscription;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindString;
import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 收款地址页面
 */
public class PayQRCodeActivity extends BaseActivity implements View.OnClickListener,
        ClipboardManager.OnPrimaryClipChangedListener, EasyPermissions.PermissionCallbacks {

    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int RC_READ_AND_WRITE_STORAGE = 124;


    public int screenWidth;

    @BindView(R.id.img_code)
    ImageView qrCode;

    @BindView(R.id.layout_code)
    LinearLayout layoutCode;

    @BindView(R.id.label_code)
    TextView labelCode;

    @BindView(R.id.txt_amount)
    EasyMoneyTextView labelAmount;

    @BindView(R.id.btn_copy)
    Button btnCopy;

    @BindView(R.id.btn_amount)
    TextView btnAmount;

    @BindView(R.id.btn_save)
    TextView btnSave;

    ClipboardManager myClipboard;
    QRCodeTask collectCodeTask;

    @BindView(R.id.select_amount)
    LinearLayout selectAmount;

    @BindView(R.id.edit_amount)
    EasyMoneyEditText editTextAmount;

    KeyboardUtil keyboardUtil;

    boolean isAmount;

//    StellarAsset stellarAsset;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, PayQRCodeActivity.class);
        activity.startActivity(intent);
    }

    @BindString(R.string.receive_bar_title)
    String title;

    @BindString(R.string.receive_btn_clear)
    String receive_btn_clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_qrcode);
        labelCode.setText(title);

        //获取屏幕的宽高
        int screenHeight = DisplayUtil.getScreenHeight(this);
        screenWidth = DisplayUtil.getScreenWidth(this);

        //码容器设计
        ViewGroup.LayoutParams params = layoutCode.getLayoutParams();
        params.height = (screenHeight / 5) * 4;
        layoutCode.setLayoutParams(params);

        //二维码尺寸设计
        int qrWidth = screenWidth / 2;
        ViewGroup.LayoutParams codeParams = qrCode.getLayoutParams();
        codeParams.width = codeParams.height = qrWidth;
        qrCode.setLayoutParams(codeParams);

        btnCopy.setOnClickListener(this::onClick);
        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        payUrl("");

        btnAmount.setOnClickListener(this::onClick);
        btnSave.setOnClickListener(this::onClick);
        keyboardUtil = new KeyboardUtil(this);
        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                if (!TextUtils.equals("0", editTextAmount.getValueString())) {
                    selectAmount.setVisibility(View.INVISIBLE);
                    labelAmount.setText(editTextAmount.getValueString());
                    labelAmount.setVisibility(View.VISIBLE);
                    isAmount = true;
                    btnAmount.setText(receive_btn_clear);
                    payUrl(editTextAmount.getValueString());
                    editTextAmount.setText("0");
                } else {
                    selectAmount.setVisibility(View.INVISIBLE);
                    editTextAmount.setText("0");
                }

            }
        });

        keyboardUtil.setOnCancelClick(new KeyboardUtil.onCancelClick() {
            @Override
            public void onCancellClick() {
                selectAmount.setVisibility(View.INVISIBLE);
                editTextAmount.setText("0");
            }
        });
    }

    private void payUrl(String amount) {
        editTextAmount.setCurrencySymbol(OkSingleton.getInstance().getSymbol(),R.drawable.ic_black_aed);
        labelAmount.setCurrencySymbol(OkSingleton.getInstance().getSymbol());
        Flowable.zip(Api.getService().payThis(amount, OkSingleton.getInstance().getCurrencyCode()),
                UniApp.getDb().keyDao().loadKey(123),
                new BiFunction<HttpResult<StellarAsset>, WalletKey, WalletKey>() {
                    @Override
                    public WalletKey apply(HttpResult<StellarAsset> t1, WalletKey t2) throws Exception {
                        t2.payUrl = t1.data.pay_url;
                        return t2;
                    }
                }).compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(PayQRCodeActivity.this))
                .subscribe(new Consumer<WalletKey>() {
                    @Override
                    public void accept(WalletKey walletKey) throws Exception {
                        builderPay(walletKey);
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));

    }

    /**
     * 收款码
     */
    public void builderPay(WalletKey walletKey) {
        labelCode.setText(walletKey.accountId);

        collectCodeTask = new QRCodeTask();
        collectCodeTask.execute(walletKey.payUrl);
    }

    @Override
    public void initBar() {
        super.initBar();
        toolbar.setTitle(title);
    }

    @Override
    public void getParams() {

    }

    @BindString(R.string.receive_btn_copy)
    String receive_btn_copy;

    @BindString(R.string.receive_btn_copied)
    String receive_btn_copied;

    @BindString(R.string.receive_btn_amount)
    String receive_btn_amount;

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_copy) {
            String text = labelCode.getText().toString();
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Flowable.timer(1, TimeUnit.SECONDS)
                    .doOnSubscribe(new Consumer<Subscription>() {
                        @Override
                        public void accept(Subscription subscription) throws Exception {
                            btnCopy.setText(receive_btn_copied);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            btnCopy.setText(receive_btn_copy);
                        }
                    });
        }

        if (v.getId() == R.id.btn_save) {
            saveImage();
        }

        if (v.getId() == R.id.btn_amount) {
            if (isAmount) {
                labelAmount.setVisibility(View.INVISIBLE);
                btnAmount.setText(receive_btn_amount);
                isAmount = false;
                labelAmount.setText("0");
                payUrl("0");
            } else {
                keyboardUtil.attachTo(editTextAmount);
                editTextAmount.setFocusable(true);
                editTextAmount.setFocusableInTouchMode(true);
                editTextAmount.requestFocus();
                selectAmount.setVisibility(View.VISIBLE);
            }

        }
    }

    /**
     * 保存图片
     */
    @AfterPermissionGranted(RC_READ_AND_WRITE_STORAGE)
    private void saveImage() {
        if (hasReadAndWritePermissions()) {
            qrCode.setDrawingCacheEnabled(true);
            Bitmap bitmap = qrCode.getDrawingCache();
            boolean isSaveSuccess = ImgUtils.saveImageToGallery(PayQRCodeActivity.this, bitmap);
            qrCode.setDrawingCacheEnabled(false);
            if (isSaveSuccess) {
                ToastUtils.show("保存图片成功");
            } else {
                ToastUtils.show("保存图片失败，请稍后重试");
            }
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permissions_storage),
                    RC_READ_AND_WRITE_STORAGE,
                    READ_AND_WRITE_STORAGE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (collectCodeTask != null) {
            collectCodeTask.cancel(true);/**/
        }

        if (myClipboard != null) {
            myClipboard.removePrimaryClipChangedListener(this);
        }
    }

    @Override
    public void onPrimaryClipChanged() {

        //TODO 剪贴板监听
    }

    /**
     * 生成二维码
     */
    class QRCodeTask extends AsyncTask<String, Integer, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... strings) {
            if (strings != null && strings.length > 0) {
                String address = strings[0];
                //生成二维码最好放子线程生成防止阻塞UI，这里只是演示
                Bitmap bitmap = CodeUtils.createQRCode(address, screenWidth / 2);
                return bitmap;
            } else {
                return null;
            }
        }

        /**
         * 展示二维码
         *
         * @param bitmap
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            GlideApp.with(PayQRCodeActivity.this).load(bitmap).into(qrCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
//        ToastUtils.show("权限授予成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(PayQRCodeActivity.this, READ_AND_WRITE_STORAGE);
    }
}
